package com.sl.springmvc.swagger.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sl.springmvc.swagger.controller.swagger.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.text.SimpleDateFormat;
import java.util.List;

@EnableWebMvc
@Configuration
@EnableSwagger2
@ComponentScan(basePackages = "com.sl.springmvc.swagger.controller")
public class SpringMVCAppConfig extends WebMvcConfigurerAdapter {

    /**
     * extend message converters.
     *
     * @param converters http message converter
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                MappingJackson2HttpMessageConverter jsonMessageConverter = (MappingJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = jsonMessageConverter.getObjectMapper();
                objectMapper.setDateFormat(new SimpleDateFormat(DateUtils.MMDDYYYYHHMMSS));
                break;
            }
        }
    }

    /**
     * View resolver.
     *
     * @return the internal resource view resolver
     */
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }


    /**
     * add resource handlers
     *
     * @param registry ResourceHandlerRegistry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/docs/**").addResourceLocations("/docs/").setCachePeriod(31556926);
        registry.addResourceHandler("/static/**").addResourceLocations("/static/").setCachePeriod(31556926);
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/").resourceChain(false);
        }
        if (!registry.hasMappingForPattern("/swagger-ui.html")) {
            registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/swagger-ui.html").resourceChain(false);
        }
        registry.addResourceHandler("/**.json").addResourceLocations("/").setCachePeriod(31556926);

    }

    /**
     * add view controllers.
     *
     * @param registry ViewControllerRegistry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/", "/docs/index.html");
    }


    /**
     * Creates the rest api.
     * 在header中放置默认的token
     *
     * @return the docket
     */
    @Bean
    public Docket createRestApi() {

        /*ParameterBuilder parameterBuilder = new ParameterBuilder();
        parameterBuilder.name("token").defaultValue(getTokenDefault()).description("safety certificate").modelRef(new ModelRef("string"))
                .parameterType("header").required(false).build();

        List<Parameter> operationParameters = new ArrayList<Parameter>();
        operationParameters.add(parameterBuilder.build());*/

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false)
                //.globalOperationParameters()
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sl.springmvc.swagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * Api info.
     *
     * @return the api info
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("SFCS DC API").description("SFCS API in Data Center").termsOfServiceUrl("").version("1.0").build();
    }

    /**
     * Gets the token default.
     *
     * @return the token default
     */
    private String getTokenDefault() {
        String tokens = System.getProperty("HYVE_SERVER_SECURITY_TOKEN");
        if (StringUtils.isBlank(tokens)) {
            tokens = System.getenv("HYVE_SERVER_SECURITY_TOKEN");
        }
        String[] tokensArray = tokens.split(",");
        if (null != tokensArray && tokensArray.length > 0) {
            return tokensArray[0];
        }
        return null;
    }
}
